from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from io import BytesIO
from PIL import Image
from chaojiying import get_code

browser = webdriver.Chrome()
# 设置浏览器窗口大小
browser.set_window_size(1400, 1400)
# 实例化一个等待时间对象, 这个时候并没有等待, 隐式等待(最大等待时间)
# 跟显示等待区别，显示等待是必须要等够指定时间
wait = WebDriverWait(browser, 5)

def get_screen_shot():
    screenshot = browser.get_screenshot_as_png()
    image = Image.open(BytesIO(screenshot))
    return image

def get_check_code_pos():
    # 获取验证码元素
    check_code = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#imgCheckCode')))
    # 获取坐标
    left_x = check_code.location['x']
    left_y = check_code.location['y'] - 300

    # 获取大小
    width = check_code.size['width']
    height = check_code.size['height']

    print('width=%d, height=%d' % (width, height))

    right_x = left_x + width
    right_y = left_y + height

    left_x *= 1.25
    left_y *= 1.72
    right_x *= 1.25
    right_y *= 1.67

    return (left_x, left_y, right_x, right_y)

def get_page():
    url = 'http://bm.e21cn.com/log/reg.aspx'
    browser.get(url)

    # 用户名
    input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#username')))
    # 清除输入框内容
    input.clear()
    input.send_keys('carmack108')

    # 密码
    input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#pwd')))
    input.clear()
    input.send_keys('12345678')

    # 确认密码
    input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#pwd_Q')))
    input.clear()
    input.send_keys('12345678')

    # 手机号
    input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#tel')))
    input.clear()
    input.send_keys('13563294483')

    # 滚动屏幕露出验证码
    script_str = 'var height = 300;  window.scrollTo(0, height);'
    # 让浏览器执行js代码
    browser.execute_script(script_str)

    # 截取全屏
    full_screen_image = get_screen_shot()
    full_screen_image.save('full_screen.png')

    left_x, left_y, right_x, right_y = get_check_code_pos()   
    print(left_x, left_y, right_x, right_y)
    
    check_code_img = full_screen_image.crop((left_x, left_y, right_x, right_y))
    check_code_img.save('check_code.png')

    # 调用超级鹰破解验证码
    code = get_code('check_code.png')
    input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#CheckCode')))
    input.clear()
    input.send_keys(code)

    button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#btn_login')))
    button.click()

def main():
    get_page()

if __name__ == '__main__':
    main()